﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Data;
using MOWebSerivce.Business;
using MOWebSerivce.Helper;
using SMSROUTER.Business;

namespace DemoMOWebService
{
    /// <summary>
    /// Summary description for SMSMOWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class SMSMOWebService : System.Web.Services.WebService
    {
        public static AntiDuplicateMO moGUID = new AntiDuplicateMO();
        public static AntiDuplicateMO moTransGUID = new AntiDuplicateMO();

        [WebMethod]
        public int SentEncryptMO(string stransID, int cooperateID, string strEncryptData, string strMD5CheckSum, ref string[][] GuidReturn, ref string strMessageReturn)
        {
            int return_value = -1;
            string strGuid = "";
            string strGuidMesasage = "";
            string[] ArrayGuidMessage;
            string[] ArrayGuid;

            //transID: Chong lap Transaction, cooperateID: Cap cho doi tac, strEncryptData: Ma hoa, strMD5CheckSum: ma kiem tra, strMessageReturn: Ma loi tra ve
            try
            {
                if (stransID != "")
                {
                    //Kiem tra stransID xem co trung khong, neu trung thi bo qua
                    if (!moTransGUID.isDuplicateGuidMo(stransID))
                    {
                        CooperateProvider cooperate = CooperateProvider.GetByID(cooperateID);
                        if (cooperate != null)
                        {
                            string strPublicPrivateKey = cooperate.MOPublicPrivateKey;
                            string bitStrengthString = strPublicPrivateKey.Substring(0, strPublicPrivateKey.IndexOf("</BitStrength>") + 14);
                            strPublicPrivateKey = strPublicPrivateKey.Replace(bitStrengthString, "");
                            int bitStrength = Convert.ToInt32(bitStrengthString.Replace("<BitStrength>", "").Replace("</BitStrength>", ""));

                            string receivedDecryptMessage = Cryptography.DecryptString(strEncryptData, bitStrength, strPublicPrivateKey);
                            string receivedMD5CheckSum = Cryptography.getMd5Hash(receivedDecryptMessage);
                            StringComparer comparer = StringComparer.OrdinalIgnoreCase;
                            //Kiểm tra nếu đúng check SUM thì cho phép thực hiện
                            if (0 == comparer.Compare(receivedMD5CheckSum, strMD5CheckSum))
                            {
                                //Nạp nội dung giải mã đưa vào trong DataSet.
                                XmlDocument xDoc = new XmlDocument();
                                xDoc.LoadXml(receivedDecryptMessage);
                                DataSet dsContent = (DataSet)Xml.Deserialize(xDoc.DocumentElement, typeof(DataSet));

                                System.Data.SqlTypes.SqlString subs;
                                System.Data.SqlTypes.SqlString message;
                                System.Data.SqlTypes.SqlString short_code;
                                System.Data.SqlTypes.SqlDateTime received_time;
                                System.Data.SqlTypes.SqlGuid sms_in_guid;
                                System.Data.SqlTypes.SqlInt32 cooperate_id;
                                System.Data.SqlTypes.SqlInt32 operator_id;
                                System.Data.SqlTypes.SqlString status;
                                //Duyệt DataSet
                                if (dsContent.Tables.Count > 0)
                                {
                                    for (int i = 0; i < dsContent.Tables[0].Rows.Count; i++)
                                    {
                                        if (dsContent.Tables[0].Columns.Contains("Subs") && dsContent.Tables[0].Rows[i]["Subs"] != null && dsContent.Tables[0].Rows[i]["Subs"].ToString() != "")
                                            subs = dsContent.Tables[0].Rows[i]["Subs"].ToString().Trim();
                                        else
                                            subs = System.Data.SqlTypes.SqlString.Null;

                                        if (dsContent.Tables[0].Columns.Contains("Message") && dsContent.Tables[0].Rows[i]["Message"] != null && dsContent.Tables[0].Rows[i]["Message"].ToString() != "")
                                            message = dsContent.Tables[0].Rows[i]["Message"].ToString().Trim();
                                        else
                                            message = System.Data.SqlTypes.SqlString.Null;

                                        if (dsContent.Tables[0].Columns.Contains("ShortCode") && dsContent.Tables[0].Rows[i]["ShortCode"] != null && dsContent.Tables[0].Rows[i]["ShortCode"].ToString() != "")
                                            short_code = dsContent.Tables[0].Rows[i]["ShortCode"].ToString().Trim();
                                        else
                                            short_code = System.Data.SqlTypes.SqlString.Null;

                                        if (dsContent.Tables[0].Columns.Contains("ReceivedTime") && dsContent.Tables[0].Rows[i]["ReceivedTime"] != null && dsContent.Tables[0].Rows[i]["ReceivedTime"].ToString() != "")
                                            received_time = Convert.ToDateTime(dsContent.Tables[0].Rows[i]["ReceivedTime"].ToString().Trim());
                                        else
                                            received_time = System.Data.SqlTypes.SqlDateTime.Null;

                                        if (dsContent.Tables[0].Columns.Contains("SmsInGUID") && dsContent.Tables[0].Rows[i]["SmsInGUID"] != null && dsContent.Tables[0].Rows[i]["SmsInGUID"].ToString() != "")
                                            sms_in_guid = new System.Data.SqlTypes.SqlGuid(dsContent.Tables[0].Rows[i]["SmsInGUID"].ToString().Trim());
                                        else
                                            sms_in_guid = System.Data.SqlTypes.SqlGuid.Null;

                                        if (dsContent.Tables[0].Columns.Contains("CooperateID") && dsContent.Tables[0].Rows[i]["CooperateID"] != null && dsContent.Tables[0].Rows[i]["CooperateID"].ToString() != "")
                                            cooperate_id = Convert.ToInt32(dsContent.Tables[0].Rows[i]["CooperateID"].ToString().Trim());
                                        else
                                            cooperate_id = System.Data.SqlTypes.SqlInt32.Null;

                                        if (dsContent.Tables[0].Columns.Contains("OperatorID") && dsContent.Tables[0].Rows[i]["OperatorID"] != null && dsContent.Tables[0].Rows[i]["OperatorID"].ToString() != "")
                                            operator_id = Convert.ToInt32(dsContent.Tables[0].Rows[i]["OperatorID"].ToString().Trim());
                                        else
                                            operator_id = System.Data.SqlTypes.SqlInt32.Null;

                                        if (dsContent.Tables[0].Columns.Contains("Status") && dsContent.Tables[0].Rows[i]["Status"] != null && dsContent.Tables[0].Rows[i]["Status"].ToString() != "")
                                            status = new System.Data.SqlTypes.SqlString(dsContent.Tables[0].Rows[i]["Status"].ToString().Trim());
                                        else
                                            status = System.Data.SqlTypes.SqlString.Null;
                                        try
                                        {
                                            if (!moGUID.isDuplicateGuidMo(stransID))
                                            {
                                                ////Luu tin nhan vao DB
                                                //SmsMoWaiting smsMoWaiting = new SmsMoWaiting();
                                                ////SmsMoPartner smsMoPartner = new SmsMoPartner();
                                                //smsMoWaiting.CooperateID = cooperate_id;
                                                //smsMoWaiting.Message = message;
                                                //smsMoWaiting.OperatorID = operator_id;
                                                //smsMoWaiting.ReceivedTime = received_time;
                                                //smsMoWaiting.ShortCode = short_code;
                                                //smsMoWaiting.SmsInGUID = sms_in_guid;
                                                //smsMoWaiting.Status = status;
                                                //smsMoWaiting.Subs = subs;
                                                //smsMoWaiting.Save();

                                                moGUID.AddMoGuid(sms_in_guid.Value.ToString());

                                                strGuid += sms_in_guid.Value.ToString() + ",";
                                                strGuidMesasage += "true\r\n";
                                                return_value = 1;
                                            }
                                            else
                                            {
                                                strGuid += sms_in_guid.Value.ToString() + ",";
                                                strGuidMesasage += "true\r\n";
                                                return_value = 1;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            return_value = -1;
                                            strMessageReturn += "[Error]=>  GUID ={" + sms_in_guid.Value.ToString() + "}; Subs = " + subs.Value + " \"" + ex.Message + "\"\r\n";
                                            strGuid += sms_in_guid.Value.ToString() + ",";
                                        }

                                    }
                                }
                            }

                            moTransGUID.AddMoGuid(stransID);
                        }
                    }

                    ArrayGuid = strGuid.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    ArrayGuidMessage = strGuidMesasage.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                    GuidReturn = new string[][] { ArrayGuid, ArrayGuidMessage };

                }
                else
                {
                    return_value = -1;
                    strMessageReturn += "stransID khong duoc rong!\r\n";
                }
            }
            catch (Exception ex)
            {
                return_value = -1;
                strMessageReturn = ex.Message;
            }

            return return_value;
        }
    }
}